
import requests
import re
import os
from urllib.parse import quote

def download_images(keyword, num_images=100):
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
    }
    encoded_keyword = quote(keyword)
    url = f"https://image.baidu.com/search/flip?tn=baiduimage&word={encoded_keyword}"
    response = requests.get(url, headers=headers)
    if response.status_code == 200:
        image_urls = re.findall('"objURL":"(.*?)",', response.text)
        count = 0
        if not os.path.exists(keyword):
            os.makedirs(keyword)
        for img_url in image_urls:
            try:
                img_response = requests.get(img_url, timeout=5000)
                if img_response.status_code == 200:
                    with open(f"{keyword}/{count}.jpg", "wb") as f:
                        f.write(img_response.content)
                    print(f"{keyword}/{count}.jpg")
                    count += 1
                    if count == num_images:
                        break
            except Exception as e:
                print(f"Error downloading image: {e}")
    else:
        print(f"Failed to fetch images. Status code: {response.status_code}")

keyword = "小鱼"
download_images(keyword)